package com.example.order.itheima;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Proxy;
import java.util.Arrays;

@Slf4j
public class ClientFactoryBean implements FactoryBean<Object> {

    private Class<?> type; // 对应的接口 的 class

    private String serviceName;//服务名称

    private String url;//点对点调用的地址
    @Override
    public Object getObject() throws Exception {
        return createPrxy();
    }

    private Object createPrxy() {
        return Proxy.newProxyInstance(
                type.getClassLoader(),
                new Class[]{type},
                (proxy,method,args) ->{
                    log.info("proxy execute ,method={},args={}",method.getName(), Arrays.toString(args));
                    if (ReflectionUtils.isObjectMethod(method)) {
                        return method.invoke(type,args);
                    }
                    // 走网络调用
                    return "-----proxy result--------";
                });
    }

    @Override
    public Class<?> getObjectType() {
        return type;
    }


    public Class<?> getType() {
        return type;
    }

    public void setType(Class<?> type) {
        this.type = type;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
